package controllers

import (
	"github.com/astaxie/beego"
	"time"
	"strconv"
	"strings"
	"math/rand"
	"image"
	"os"
	"image/jpeg"
	"image/png"
	"log"
	"github.com/BurntSushi/graphics-go/graphics"
	"fmt"
)

type JsonReturnData_Message struct {
	Code int
	Data string
}

func Json_Message(c *beego.Controller, code int, data string) {
	json_error := JsonReturnData_Message{Code:code, Data:data }
	c.Data["json"] = &json_error
	c.ServeJSON()
	c.StopRun()
}

func Message(c *beego.Controller, redirectURL string, message string, ExtraInfo string, back bool) {
	c.Data["Message"] = message
	c.Data["TargetURL"] = redirectURL
	if back {
		c.Data["script"] = `<script type="text/javascript">
		function back(secs) {
		var jumpTo = document.getElementById('jumpTo');
		jumpTo.innerHTML = secs;
		if (--secs > 0) {
		setTimeout("back(" + secs + ")", 1000);
		}
else {
history.go(-1);
}
}
back(3);
</script>`
	} else {
		c.Data["script"] = fmt.Sprintf(`<script type="text/javascript">
		countDown(3, "%s");
	</script>`, redirectURL)
	}
	c.TplName = "message.html"
	c.Render()
	c.StopRun()
}

func RandString(length int) string {
	rand.Seed(time.Now().UnixNano())
	rs := make([]string, length)
	for start := 0; start < length; start++ {
		t := rand.Intn(3)
		if t == 0 {
			rs = append(rs, strconv.Itoa(rand.Intn(10)))
		} else if t == 1 {
			rs = append(rs, string(rand.Intn(26) + 65))
		} else {
			rs = append(rs, string(rand.Intn(26) + 97))
		}
	}
	return strings.Join(rs, "")
}

// LoadImage decodes an image from a file.
func LoadImage_FromPath(path string) (img image.Image, err error) {
	file, err := os.Open(path)
	if err != nil {
		return
	}
	defer file.Close()
	img, _, err = image.Decode(file)
	if err != nil {
		img, err = jpeg.Decode(file)
	}
	return
}

func SaveImage(path string, img image.Image) (err error) {
	// 需要保存的文件
	imgfile, err := os.Create(path)
	defer imgfile.Close()
	// 以PNG格式保存文件
	err = png.Encode(imgfile, img)
	if err != nil {
		log.Fatal(err)
	}
	return
}

func GenerateTumbnail(filepath string, structName string, Id int64, width int, height int) {
	path := beego.AppConfig.String("uploadspath")
	directory := "/thumbnail/" + strings.ToLower(structName)
	totalPath := path + directory + "/" + strconv.FormatInt(Id, 10) + "_" + strconv.Itoa(width) + "x" + strconv.Itoa(height) + ".png"
	os.MkdirAll(path + directory, 0777)
	src, err := LoadImage_FromPath(filepath)
	if err != nil {
		return
	}
	// 缩略图的大小
	dst := image.NewRGBA(image.Rect(0, 0, width, height))
	// 产生缩略图
	err = graphics.Thumbnail(dst, src)
	if err != nil {
		return
	}
	SaveImage(totalPath, dst)
}
func TacleUeditor(c *beego.Controller) {
	action := c.GetString("action")
	if action == "config" {
		c.Data["json"] = map[string]interface{}{
			"imageUrl": "http://localhost:8082/article/multitextimageUp?action=uploadimage",
			"imagePath": "/",
			"imageFieldName": "upfile",
			"imageMaxSize": 2048,
			"imageActionName":"uploadimage",
			"imagePathFormat":"/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
			"imageUrlPrefix":"",
			"imageAllowFiles":[]string{".png", ".jpg", ".jpeg", ".gif", ".bmp"}}

		c.ServeJSON()
		c.StopRun()
	}
	if action != "uploadimage" {
		Json_Message(c, 1, "not surport" + action)
	}
}
